<template>
<div>
  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
  </el-breadcrumb>
  <el-card class="box-card">
    <el-row :gutter="20">
      <el-col :span="7">
        <el-input placeholder="请输入内容">
          <el-button slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="openAddUSerDialog">添加用户</el-button>
      </el-col>
    </el-row>
    <el-table
      border
      :data="userList"
      style="width: 100%">
      <el-table-column
        prop="id"
        label="ID"
        width="180">
      </el-table-column>
      <el-table-column
        prop="username"
        label="姓名"
        width="180">
      </el-table-column>
      <el-table-column
        prop="mobile"
        label="手机">
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮箱">
      </el-table-column>
      <el-table-column
        prop="create_time"
        label="创建时间">
      </el-table-column>
      <el-table-column
        prop="mg_state"
        label="状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            @change="changeUserState(scope.row)"
            active-color="#13ce66">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="role_name"
        label="角色">
      </el-table-column>
      <el-table-column
      fixed="right"
      width="200">
      <template slot-scope="scope">
        <el-button type="primary" icon="el-icon-edit" size="mini" @click="openEditUserDialog(scope.row)">编辑</el-button>
        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)">删除</el-button>
      </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryParam.pagenum"
      :page-sizes="[2, 20, 50, 100]"
      :page-size="queryParam.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </el-card>
<el-dialog
  title="添加用户"
  :visible.sync="addDialogVisible"
  @close="closeHandle('addUserFormRef')"
  width="50%">
  <el-form ref="addUserFormRef" :model="addUserForm" :rules="addUserRules" label-width="80px">
    <el-form-item label="用户名称" prop="username">
      <el-input v-model="addUserForm.username"></el-input>
    </el-form-item>
    <el-form-item label="用户密码" prop="password">
      <el-input v-model="addUserForm.password"></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="addUserForm.email"></el-input>
    </el-form-item>
    <el-form-item label="手机号" prop="mobile">
      <el-input v-model="addUserForm.mobile"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
</el-dialog>
<el-dialog
  title="编辑用户"
  :visible.sync="editDialogVisible"
  @close="closeHandle('editUserFormRef')"
  width="50%">
  <el-form ref="editUserFormRef" :model="editUserForm" :rules="editUserRules" label-width="80px">
    <el-form-item label="用户名称" prop="username">
      <el-input v-model="editUserForm.username" disabled></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="editUserForm.email"></el-input>
    </el-form-item>
    <el-form-item label="手机号" prop="mobile">
      <el-input v-model="editUserForm.mobile"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUser">确 定</el-button>
  </span>
</el-dialog>
</div>
</template>
<script>
export default {
  data () {
    var validatEmail = (rule, value, callback) => {
      const emailReg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (emailReg.test(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的Email'))
      }
    }
    var validatMobile = (rule, value, callback) => {
      const mobileReg = /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (mobileReg.test(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的手机号'))
      }
    }
    return {
      total: 0,
      queryParam: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      addDialogVisible: false,
      editDialogVisible: false,
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editUserForm: {},
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 5, max: 15, message: '长度在 5 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: validatEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validatMobile, trigger: 'blur' }
        ]
      },
      editUserRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: validatEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validatMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      try {
        const { data: res } = await this.$http.get('/users', { params: this.queryParam })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.userList = res.data.users
        this.total = res.data.total
      } catch (err) {
        this.$message.error('网络连接中断，请联系管理员')
      }
    },
    handleSizeChange (val) {
      this.queryParam.pagesize = val
      this.getUserList()
    },
    handleCurrentChange (val) {
      this.queryParam.pagenum = val
      this.getUserList()
    },
    openAddUSerDialog () {
      this.addDialogVisible = true
    },
    openEditUserDialog (userInfo) {
      this.editUserForm = userInfo
      console.log(this.editUserForm)
      this.editDialogVisible = true
    },
    closeHandle (ref) {
      this.$refs[ref].resetFields()
    },
    addUser () {
      this.$refs.addUserFormRef.validate(async vaild => {
        if (vaild) {
          const { data: res } = await this.$http.post('/users', this.addUserForm)
          if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
          this.$message.success('添加用户成功')
          this.addDialogVisible = false
          this.getUserList()
        }
      })
    },
    editUser () {
      this.$refs.editUserFormRef.validate(async vaild => {
        if (vaild) {
          const { data: res } = await this.$http.put('/users/' + this.editUserForm.id, this.editUserForm)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success('编辑用户成功')
          this.editDialogVisible = false
          this.getUserList()
        }
      })
    },
    async deleteUser (id) {
      const result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(id)
      console.log(result)
      if (result === 'cancel') return false
      const { data: res } = await this.$http.delete('/users/' + id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success('删除成功')
      this.getUserList()
    },
    async changeUserState (userInfo) {
      console.log(userInfo)
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.state = !userInfo.state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('用户状态设置成功')
    }
  }
}
</script>
<style lang="less" scoped>
  .el-table {
    margin-top: 20px;
  }
</style>
